import {ComponentOptions} from "vue/types/options";
import typeOfUtils from "../utils/type-of-utils";
import ShowTooltip from "../directive/VshowTooltip/VshowTooltip";

export const SelectObjectMixin: ComponentOptions<any> = {
  // 自定义指令，这里定义局部指令
  directives: {
    ShowTooltip,
  },
  model: {
    // 支持双向绑定
    prop: 'value',
    event: 'update:value',
  },
  props: {
    value: {
      type: [Array, Object],
      default: () => [],
    },
    title: {
      type: String,
      default: '数据选择',
    },
    disabled: Boolean,
    selectMultiple: Boolean, // 选择 true为多选，false为单选
    selectShowView: {
      // 右边选中显示的值 接受选中的值，返回显示的值
      type: Function, // 参数：表格item，返回用于显示
      default: (item) => item.name,
    },
    selectEquals: {
      // 判断选中的值唯一性 (oldSelectItem,newSelectItem)=>Boolean
      type: Function,
      default: (oldItem, newItem) => oldItem.id === newItem.id,
    },
  },
  watch: {
    selectData: {
      handler(val) {
        if (this.selectMultiple) {
          this.$emit('update:value', val);
        } else {
          if (typeOfUtils.isNotEmpty(val)) {
            this.$emit('update:value', val[0]);
          } else {
            this.$emit('update:value', this.value);
          }
        }
        this._setRowSelect();
      },
      deep: true,
    },
    value: {
      handler(val, old) {
        this._valueRefChange(val, old)
        this._initSelectData();
        if (val !== old && typeOfUtils.isEmpty(val)) {
          this._clearSelect();
        }
      },
    },
  },
  computed: {
    /**
     * 这个肯定要重写
     * @param value
     * @param dragDialogShow
     */
    // @ts-ignore
    showSelectData({value, dragDialogShow}) {
      let result = this.selectData;
      return result.filter((i) => {
        if (this.selectMultiple) {
          if (this.selectShowView(i).includes(this.filter)) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      });
    },
  },
  data() {
    return {
      dragDialogShow: false,
      selectData: [], // 选中的值
      filter: '',
    }
  },
  methods: {
    _initSelectData() {
      if (typeOfUtils.isArray(this.value)) {
        this.$set(this, 'selectData', this.value);
      } else {
        this.selectData.splice(0, this.selectData.length)
        if (typeOfUtils.isNotEmpty(this.value)) {
          this.selectData.push(this.value);
        }
      }
    },
    /**
     * 重写
     * @param val
     * @param oldVal
     */
    _valueRefChange(val: object | object[] | undefined, oldVal: object | object[] | undefined) {

    },
    /**
     * 重写
     */
    _clearSelect() {
      this.selectData.splice(0, this.selectData.length)
    },
    /**
     * 重写
     */
    _setRowSelect() {

    },
  }
}
